﻿#region Using
/*
=============================================================================
Author:魏宝辉通过CodeSmithe生成
CreatedTime:2012-11-3
Description:CQuery_FormList.aspx.cs页面代码
=============================================================================	
*/

using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using FineUI;
using FTchina.Logic;
using FTchina.Library;
using FTchina.Models;
using PWMIS.DataMap.Entity;
using PWMIS.DataProvider.Data;
using PWMIS.DataProvider.Adapter;
using PWMIS.Common;
using System.Collections.Generic;
using AspNet = System.Web.UI.WebControls;
using System.Collections;
using System.Linq;
#endregion
public partial class CQuery_FormListaction : BasePage
{
    List<Cquery_ColumList> Modlist;//修改报表时存放字段集合
    bool IsNew = true;//默认为新增模式
    protected void Page_Load(object sender, EventArgs e)
    {
        string id = RequestHelper.SafeRequest(Request["Rid"]);
        //LogHelper.Debug("Page_Load" + id);
        if (id.Length > 0)
        {
            IsNew = false;//不是新增模式，编辑模式
        }
        if (txbguid.Text == "")
        {//新建，需要统一guid
            txbguid.Text = Guid.NewGuid().ToString();
        }

        if (!IsPostBack)
        {
            LoadData();
            if (id.Length > 0)
            {
                ShowModData(id);
            }
        }

    }
    private void LoadData()
    {

        // 关闭按钮的客户端脚本：
        // 1. 首先确认窗体中表单是否被修改（如果已经被修改，则弹出是否关闭的确认对话框）
        // 2. 然后关闭本窗体，回发父窗体
        btnClose.OnClientClick = ActiveWindow.GetConfirmHidePostBackReference();
        ControlBindHelper.DropDownListBind(ddlconnId, "CQuery_ConnString", "ConnName");
        lblshuoming.Text = @"外联唯一字段系统自动置为不显示、关闭状态"
                           + "<br>默认值可用关键字："
                           + "$姓名$=" + MasterHelper.UName
                           + ",$账户$=" + MasterHelper.UID
                           + ",$Now$=" + DateTime.Now.ToString()
                           + "<br>下拉列表默认值样例：男^1,女^0 其中，显示为男、女，值为1、0"
                           + "<br>操作表需真实存在。";


    }
    private void ShowModData(string ItemID)
    {
        FTchina.Models.CQuery_FormList mCQuery_FormList = FTchina.BLL.CQuery_FormListManager.GetCQuery_FormListById(Convert.ToInt32(ItemID));
        if (mCQuery_FormList != null)
        {
            txbid.Text = mCQuery_FormList.Id.ToString().Trim();
            ddlconnId.SelectedValue = mCQuery_FormList.ConnID;
            txbreportName.Text = mCQuery_FormList.ReportName.ToString().Trim();
            txbshortView.Text = mCQuery_FormList.ShortView.ToString().Trim();
            txbsqlString.Text = mCQuery_FormList.SqlString;

            txbguid.Text = mCQuery_FormList.Guid;//将本次的GUID赋值，供其他地方使用

            #region 将相关的列都查出来
            Cquery_ColumList ccl = new Cquery_ColumList();
            OQLCompare cmp = new OQLCompare(ccl);
            OQLCompare cmpresult = (cmp.Comparer(ccl.Guid, OQLCompare.CompareType.Equal, mCQuery_FormList.Guid)
                & cmp.Comparer(ccl.Isinuse, OQLCompare.CompareType.Equal, "1")
            );//guid isinuse 过滤条件

            OQL q = new OQL(ccl);
            q.Select().Where(cmpresult).OrderBy(ccl.Paixu, "desc");
            Modlist = EntityQuery<Cquery_ColumList>.QueryList(q, ccl);

            Grid1.RowDataBound += new EventHandler<GridRowEventArgs>(Grid1_RowDataBound);
            Grid1.DataSource = Modlist;
            Grid1.DataBind();

            FillDDLColum();//绑定排序字段
            ddlOrderColum.SelectedValue = mCQuery_FormList.OrderColum;
            #endregion
        }
        else
        {
            AlertLogic.ShowResultAndRedirect("无数据！", "提示", HttpContext.Current.Request.Path.ToString(), false);
        }
    }


    protected void btnSaveContinue_Click(object sender, EventArgs e)
    {
        // 1. 这里放置保存窗体中数据的逻辑
        FTchina.Models.CQuery_FormList mCQuery_FormList = new FTchina.Models.CQuery_FormList();
        mCQuery_FormList.Id = txbid.Text.Trim() == "" ? 0 : Convert.ToInt32(txbid.Text);
        if (mCQuery_FormList.Id == 0)
        {//第一次添加是创建，修改不能动
            mCQuery_FormList.Guid = txbguid.Text;
            mCQuery_FormList.LuruId = MasterHelper.Luruid;
        }
        mCQuery_FormList.ConnID = ddlconnId.SelectedValue;
        mCQuery_FormList.ReportName = txbreportName.Text.Trim();
        mCQuery_FormList.ShortView = txbshortView.Text.Trim();
        mCQuery_FormList.SqlString = txbsqlString.Text;
        mCQuery_FormList.OrderColum = ddlOrderColum.SelectedValue;
        if (FTchina.BLL.CQuery_FormListManager.AddOrUpdateCQuery_FormList(mCQuery_FormList) > 0)
        {//报表信息保存成功，才能保存列的信息
            // LogHelper.Debug("报表信息保存成功，才能保存列的信息");
            SaveColums();

            ReportLogic.UpdateSqlString(txbguid.Text, txbsqlString.Text);
        }
        else
        {
            // LogHelper.Debug("报表信息保存成功，才能保存列的信息----失败");
        }
        // 2. 关闭本窗体，然后回发父窗体
        PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
    }

    /// <summary>
    /// 绑定排序字段
    /// </summary>
    protected void FillDDLColum()
    {
        ddlOrderColum.DataSource = Modlist;
        ddlOrderColum.DataTextField = "ColumID";
        ddlOrderColum.DataValueField = "ColumID";
        ddlOrderColum.DataBind();
    }


    protected void Grid1_RowDataBound(object sender, FineUI.GridRowEventArgs e)
    {
        if (Modlist.Count > 0)
        {//如果有需要绑定显示的数据
            for (int i = 0, count = Grid1.Rows.Count; i < count; i++)
            {
                GridRow row = Grid1.Rows[i];
                ((AspNet.TextBox)row.FindControl("txbColumName")).Text = Modlist[i].ColumName;
                ((AspNet.DropDownList)row.FindControl("ddlQueryType")).SelectedValue = Modlist[i].QueryType;
                ((AspNet.CheckBoxList)row.FindControl("cblIsQuery")).SelectedValue = Modlist[i].IsQuery;
                ((AspNet.CheckBoxList)row.FindControl("cblIsShow")).SelectedValue = Modlist[i].IsShow;
                ((AspNet.TextBox)row.FindControl("txbPaixu")).Text = Modlist[i].Paixu.ToString();
                ((AspNet.TextBox)row.FindControl("txbDefaultValue")).Text = Modlist[i].DefaultValue;

            }
        }
    }

    /// <summary>
    /// 保存列
    /// </summary>
    protected void SaveColums()
    {

        string OrderColum = ddlOrderColum.SelectedValue;////外联唯一字段，不能展示，因为不需要手动更改

        for (int i = 0, count = Grid1.Rows.Count; i < count; i++)
        {
            Cquery_ColumList ccl = new Cquery_ColumList();

            GridRow row = Grid1.Rows[i];

            object[] rowDataKeys = Grid1.DataKeys[i];
            ccl.ColumID = rowDataKeys[1].ToString();
            ccl.Isinuse = "1";
            ccl.Id = Convert.ToInt64(rowDataKeys[0]);
            // LogHelper.Debug(ccl.Id + "--" + ccl.Isinuse + "--" + ccl.ColumID);
            ccl.Guid = txbguid.Text;


            AspNet.DropDownList _ddlQueryType = (AspNet.DropDownList)row.FindControl("ddlQueryType");
            ccl.QueryType = _ddlQueryType.SelectedValue;

            AspNet.TextBox _txbColumName = (AspNet.TextBox)row.FindControl("txbColumName");
            ccl.ColumName = _txbColumName.Text;

            if (ccl.ColumID == OrderColum)
            {//外联唯一字段，不能展示，因为不需要手动更改
                ccl.IsQuery = "0";
            }
            else
            {
                AspNet.CheckBoxList _cblIsQuery = (AspNet.CheckBoxList)row.FindControl("cblIsQuery");
                if (_cblIsQuery.SelectedItem == null)
                {
                    ccl.IsQuery = "0";
                }
                else
                {
                    ccl.IsQuery = _cblIsQuery.SelectedItem.Value;
                }
            }

            if (ccl.ColumID == OrderColum)
            {//外联唯一字段，不能展示，因为不需要手动更改
                ccl.IsShow = "0";
            }
            else
            {
                ///此处ISshow是用在Form表单中，是否Enable
                AspNet.CheckBoxList _cblIsShow = (AspNet.CheckBoxList)row.FindControl("cblIsShow");
                if (_cblIsShow.SelectedItem == null)
                {
                    ccl.IsShow = "0";
                }
                else
                {
                    ccl.IsShow = _cblIsShow.SelectedItem.Value;
                }
            }

            AspNet.TextBox _txbPaixu = (AspNet.TextBox)row.FindControl("txbPaixu");
            ccl.Paixu = Convert.ToInt64(_txbPaixu.Text);

            AspNet.TextBox _txbDefaultValue = (AspNet.TextBox)row.FindControl("txbDefaultValue");
            ccl.DefaultValue = _txbDefaultValue.Text;

            FTchina.BLL.Cquery_ColumListManager.AddOrUpdateCquery_ColumList(ccl);
        }




    }
    /// <summary>
    /// 生成列按钮
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnGeren_click(object sender, EventArgs e)
    {
        //初始化数据源模型
        CQuery_ConnString ccs = new CQuery_ConnString();
        ccs.Id = Convert.ToInt64(ddlconnId.SelectedValue);
        EntityQuery<CQuery_ConnString> query = new EntityQuery<CQuery_ConnString>(ccs);
        query.FillEntity(ccs);

        //获取数据源类型
        DBMSType dbtype = DBTypeLogic.getDbmsTypeByString(ccs.DbType);

        ///实例化操作助手
        AdoHelper adohelper = MyDB.GetDBHelper(dbtype, ccs.ConnString);

        //获取列，取一行数据就行
        string sqlFormat = "select * from (select * from {0} x_x) t_t";
        string sql = string.Format(sqlFormat, txbsqlString.Text);
        string sqlSingle = PWMIS.Common.SQLPage.MakeSQLStringByPage(dbtype, sql, "", 1, 1, 1);
        //Alert.Show(sqlSingle);
        DataTable dt = adohelper.ExecuteDataSet(sqlSingle).Tables[0];


        //TODO:获取表结构，得到主键，把主键排除。因为主键不能更改。

        //获取字段数据，新增或者提取已设置过的老数据
        List<Cquery_ColumList> list = GetColums(dt);

        Modlist = list;//把新的列表数据赋值给公用的属性，绑定时调用
        Grid1.RowDataBound += new EventHandler<GridRowEventArgs>(Grid1_RowDataBound);

        Grid1.RecordCount = list.Count;
        Grid1.DataSource = list;
        Grid1.DataBind();

        FillDDLColum();//绑定排序字段

        //Alert.Show(adohelper.ExecuteDataSet("select * from sms_log").Tables[0].Rows.Count.ToString());

    }

    /// <summary>
    /// 提取字段数据
    /// </summary>
    /// <param name="NewColumsdt"></param>
    /// <returns></returns>
    private List<Cquery_ColumList> GetColums(DataTable NewColumsdt)
    {
        List<Cquery_ColumList> tmp = new List<Cquery_ColumList>();

        #region 获取数据库中已有的字段集合

        Cquery_ColumList cclist = new Cquery_ColumList();
        OQLCompare cmp = new OQLCompare(cclist);
        OQLCompare cmpresult = cmp.Comparer(cclist.Guid, OQLCompare.CompareType.Equal, txbguid.Text);
        OQL q = new OQL(cclist);
        q.Select().Where(cmpresult).OrderBy(cclist.Paixu, "desc");
        List<Cquery_ColumList> Modlist = EntityQuery<Cquery_ColumList>.QueryList(q, cclist);
        #endregion

        #region 比对所有的字段，找到原有的字段，新加的字段赋值给AddColums
        if (Modlist.Count > 0)
        {//数据库中有原来的数据
            foreach (DataColumn dc in NewColumsdt.Columns)
            {
                if (dc.ColumnName.ToUpper() == "R_N") continue;
                foreach (Cquery_ColumList ccl in Modlist)
                {
                    if (ccl.ColumID == dc.ColumnName.ToString().ToUpper())
                    {//如果匹配，说明是老数据，提取
                        tmp.Add(ccl);
                    }
                }
                //第一次循环把老数据添加完毕，再跑一次比对新数据，要不然会重复
                foreach (Cquery_ColumList ccl in Modlist)
                {
                    if (ccl.ColumID != dc.ColumnName.ToString().ToUpper())
                    {

                        Cquery_ColumList cclx = new Cquery_ColumList();
                        cclx.Id = 0;
                        cclx.ColumID = dc.ColumnName.ToString().ToUpper();
                        cclx.Paixu = 20;
                        cclx.IsQuery = "1";
                        cclx.IsShow = "1";
                        cclx.Isinuse = "1";

                        if (!tmp.Contains(cclx, ColumIDComparer.Default))
                        {//去重
                            tmp.Add(cclx);
                        }
                    }
                }
            }
        }
        else
        {//如果原来没有的话，那就全部放到新加
            foreach (DataColumn dc in NewColumsdt.Columns)
            {
                if (dc.ColumnName.ToUpper() == "R_N") continue;
                Cquery_ColumList cclx = new Cquery_ColumList();
                cclx.Id = 0;
                cclx.ColumID = dc.ColumnName.ToString().ToUpper();
                cclx.Paixu = 10;
                cclx.IsQuery = "1";
                cclx.IsShow = "1";
                cclx.Isinuse = "1";
                tmp.Add(cclx);

            }
        }
        #endregion

        #region 将没有用到的字段更新Isinuse
        IEnumerable<Cquery_ColumList> nouselist = Modlist.Union<Cquery_ColumList>(tmp).Except<Cquery_ColumList>(tmp);

        foreach (Cquery_ColumList itemx in nouselist)
        {
            itemx.Isinuse = "0";
            EntityQuery<Cquery_ColumList> query = new EntityQuery<Cquery_ColumList>(itemx);
            query.Update(itemx);
        }
        #endregion

        return tmp;
    }
    public class ColumIDComparer : IEqualityComparer<Cquery_ColumList>
    {
        public static ColumIDComparer Default = new ColumIDComparer();
        #region IEqualityComparer<PopupModel> 成员
        public bool Equals(Cquery_ColumList x, Cquery_ColumList y)
        {
            return x.ColumID.Equals(y.ColumID);
        }
        public int GetHashCode(Cquery_ColumList obj)
        {
            return obj.GetHashCode();
        }
        #endregion
    }



}






